#!/bin/bash
###############################################################
## make a list for the skimmed ntuples ##
## usage: ./make_list.sh $1 $2
##        arg1: Runlist (a list of datasets you have skimmed)
##        arg2: data or mc
## Lailin, Ann Arbor, 1.2013
###############################################################

if [ $# -lt 1 ]; then
    echo "usage: ./make_list.sh arg1 arg2"
    echo "arg1: input_list"
    echo "arg2: data or mc"
    exit 0
fi

input_list_log=$1
data=$2
datadir="$data"_list
listdir=Skimlist
if [ ! -d $listdir ]; then mkdir $listdir; fi
if [ ! -d "$listdir"/"$datadir" ]; then mkdir "$listdir"/"$datadir"; fi

datehm=yymmddhhmm

while read dset; do
  echo "Info => dataset: $dset"
  ddset=`echo $dset | sed 's/\///g'`
  list=$ddset.list
  outDS=user.lxu.output.$datehm.$ddset
  # prun requires the outDS length no more than 132
  len=`echo $outDS | wc -m`
  if [ $len -gt 132 ]; then
    new_outDS=${outDS//_/}
    outDS=$new_outDS
    len=`echo $outDS | wc -m`
    if [ $len -gt 132 ]; then
       new_outDS=${outDS:0:131}
       outDS=$new_outDS
    fi
  fi

  real_outDS=${outDS/"$datehm"/*}
  echo "Info => real_dataset: $real_outDS"
  #if [ ! -d "Output/$real_outDS*" ]; then
  #  new_real_outDS=${real_outDS//_/}
  #  real_outDS=$new_real_outDS
  #fi
  for output in `ls -d Output/$real_outDS*`; do
    echo "Info => creat list for: $output"
    path=`readlink -f $output`
    name=`basename $output` 
    ls $path/*tree.root* >> $list
  done

  mv $list "$listdir"/"$datadir"

done < $input_list_log

runlist="$data"12_gridskim_list.txt
if [ -f "$runlist" ]; then
   rm "$runlist"
fi

for list in `ls $listdir/$datadir/*`; do
  len=`wc -l $list | cut -f1 -d' '`
  if [ "$len" == "0" ]; then echo "empty: $list" >> empty_list; continue; fi
  path=`readlink -f "$listdir"/"$datadir"`
  name=`basename $list`
  echo "$path/$name" >> "$runlist"
done

mv "$runlist" "$listdir"

echo "Done"
